<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const orders = [
        {
          id: 1,
          name: 'John Smith',
          address: '123 Main St',
          status: 'created',
          log: [
            {
              status: 'created',
              time: '2023-02-16 12:30:00',
            },
          ],
        },
        {
          id: 2,
          name: 'Jane Doe',
          address: '456 Second St',
          status: 'packed',
          log: [
            {
              status: 'created',
              time: '2023-02-16 10:00:00',
            },
            {
              status: 'packed',
              time: '2023-02-16 12:30:00',
            },
          ],
        },
        {
          id: 3,
          name: 'Bob Johnson',
          address: '789 Third St',
          status: 'shipped',
          log: [
            {
              status: 'created',
              time: '2023-02-15 10:00:00',
            },
            {
              status: 'packed',
              time: '2023-02-15 12:00:00',
            },
            {
              status: 'shipped',
              time: '2023-02-16 9:00:00',
            },
          ],
        },
      ]

      // 一、
      function getOrdersByStatus(status) {
        const result = orders
          .filter((order) => order.status === status)
          .map((order) => {
            const filteredLog = order.log.filter((log) => log.status === status)
            return {
              id: order.id,
              name: order.name,
              address: order.address,
              status: order.status,
              log: filteredLog,
            }
          })
          .sort((a, b) => a.id - b.id)
        return result
      }
      getOrdersByStatus('shipped')
      console.log(getOrdersByStatus('shipped'))

      // 二、
      function getOrderStatusHistory(id) {
        const order = orders.find((order) => order.id === id)
        if (!order) {
          return ''
        }
        const sortedLog = order.log.sort((a, b) => {
          const timeA = new Date(a.time).getTime()
          const timeB = new Date(b.time).getTime()
          return timeA - timeB
        })
        const history = sortedLog
          .map((log) => {
            const timeString = log.time
            const statusString = log.status
            return `[${timeString}] ${statusString}`
          })
          .join('\n')
        return history
      }
      console.log(getOrderStatusHistory(2));
    </script>
  </body>
</html>
